from flask import render_template, redirect, g, request, jsonify, current_app, abort

from info import constants, db
from info.models import Category, News, User
from info.modules.profile import profile_blu
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET


@profile_blu.route("/other_news_list")
def other_news_list():
    """
    其他用户新闻列表
    :return:
    """
    # 1.取参数
    page = request.args.get("p",1)
    other_id = request.args.get("user_id")
    # 2.判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")
    if not other_id:
        return jsonify(errno= RET.NODATA,errmsg = "用户不存在")
    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = other.news_list.paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        news_li = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    news_dict_li = []
    for new in news_li:
        news_dict_li.append(new.to_basic_dict())
    data = {
        "news_list":news_dict_li,
        "current_page":current_page,
        "total_page":total_page
    }
    return jsonify(errno= RET.OK,errmsg = "OK",data=data)



@profile_blu.route("/other_info")
@user_login_data
def other_info():
    """
    其他用户的数据展示
    :return:
    """
    # 1.查询其他人的用户信息
    user = g.user
    other_id = request.args.get("user_id")
    if not other_id:
        abort(404)
    # 2.查询指定用户的信息
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)

    if not other:
        abort(404)

    is_followed = False
    # ｉｆ当前有作者并且已经关注过该作者
    if other and user:
        if other in user.followed:
            is_followed = True

    data={
        "user":g.user.to_dict() if g.user else None,
        "other_info":other.to_dict(),
        "is_followed":is_followed
    }

    return render_template("news/other.html",data=data)


@profile_blu.route("/user_follow")
@user_login_data
def user_follow():
    """
    我的关注
    :return:
    """
    # 1.取到页数
    page = request.args.get("p",1)
    # 2.判断
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page =1
    # 取到当前登录用户
    user = g.user
    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        follows = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    user_dict_li = []
    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())


    data = {
        "users":user_dict_li,
        "current_page":current_page,
        "total_page":total_page
    }
    return  render_template("news/user_follow.html",data = data)




@profile_blu.route("/news_list")
@user_login_data
def news_list():
    """
    新闻列表
    :return:
    """
    # 1.获取参数
    page = request.args.get("p",1)
    # 2.校验参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    # 3.查询新闻
    user = g.user
    paginate_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        paginate_li = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    paginate_dict_li = []
    for new in paginate_li:
        paginate_dict_li.append(new.to_review_dict())
    data = {
        "news_list":paginate_dict_li,
        "current_page":current_page,
        "total_page":total_page
    }

    return render_template("news/user_news_list.html",data=data)


@profile_blu.route("/news_release",methods=["GET","POST"])
@user_login_data
def news_release():
    """
    新闻发布
    :return:
    """
    user = g.user
    if request.method == "GET":
        # 加载新闻分类数据
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        category_dict_li = []
        for category in categories:
            category_dict_li.append(category.to_dict())
        # 移除最新这个分类
        category_dict_li.pop(0)

        data = {
            "user":user.to_dict(),
            "categories":category_dict_li
        }
        return render_template("news/user_news_release.html",data=data)
    # 1. 获取要提交的数据
    #标题
    title = request.form.get("title")
    # 新闻来源
    source = "个人发布"
    # 摘要
    digest = request.form.get("digest")
    # 新闻内容
    content = request.form.get("content")
    # 索引图片
    index_image = request.files.get("index_image")
    # 分类id
    category_id = request.form.get("category_id")

    # 2.校验参数
    if not all([title,source,digest,content,index_image,category_id]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3.取到图片，将图片上传到七牛云
    try:
        index_image_data = index_image.read()
        key = storage(index_image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    news = News()
    news.title = title
    news.source = source
    news.digest = digest
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX+key
    news.category_id = category_id
    news.user_id = user.id
    # 1代表审核状态
    news.status = 1
    # 保存到数据库中
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")
    return jsonify(errno=RET.OK, errmsg="成功")


@profile_blu.route("/collection")
@user_login_data
def user_collection():
    """
    用户收藏新闻
    :return:
    """
    user = g.user
    # 1.获取参数
    page = request.args.get("p",1)
    # 2.判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    # 3.查询当前用户收藏了的新闻
    news_list = []
    current_page = 1
    total_page = 1
    try:
        # 通过user对象中的collection_news(表示所有收藏新闻的数据),通过paginate方法分页查询
        paginate = user.collection_news.paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        current_page = paginate.page
        total_page = paginate.pages
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)
    news_dict_li = []
    for new in news_list:
        news_dict_li.append(new)

    data = {
        "user":user.to_dict(),
        "current_page":current_page,
        "total_page":total_page,
        "collections":news_dict_li
    }

    return render_template("/news/user_collection.html",data=data)


@profile_blu.route("/pass_info",methods=['GET','POST'])
@user_login_data
def pass_info():
    """
    修改密码
    :return:
    """
    user = g.user
    if request.method =="GET":
        return render_template("/news/user_pass_info.html",data ={"user":user.to_dict()})
    # 1.获取参数
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")

    # 2.判断参数
    if not all([old_password,new_password]):
        return jsonify(errno=RET.PARAMERR,errmsg = "参数错误")
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原密码错误")

    # 3.设置新密码
    user.password = new_password
    return jsonify(errno=RET.OK, errmsg="设置成功")



@profile_blu.route("/pic_info",methods=['GET','POST'])
@user_login_data
def pic_info():
    """
    上传头像
    :return:
    """
    user = g.user
    if request.method =="GET":
        return render_template("news/user_pic_info.html",data={"user":user.to_dict()})
    #　如果是ＰＯＳＴ则表示修改头像
    # 1.取到上传的图片
    try:
        avatar = request.files.get("avatar")
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
    # 2.上传头像
    # 使用自己封装的storage方法去上传,保存一个键的值
    try:
        key = storage(avatar)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传失败")

    # 3.保存头像地址
    user.avatar_url=key
    return jsonify(errno=RET.OK, errmsg="OK",data={"avatar_url":constants.QINIU_DOMIN_PREFIX+key})

@profile_blu.route("/base_info",methods=['GET','POST'])
@user_login_data
def base_info():

    if request.method=="GET":
        return render_template("news/user_base_info.html",data={"user":g.user.to_dict()})

    # 代表用户修改数据
    # 1.获取参数
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")

    # 2.校验参数
    if not all([nick_name,signature,gender]):
        return jsonify(errno = RET.PARAMERR,errmsg = "参数错误")
    if gender not in("WOMAN","MAN"):
        return jsonify(errno = RET.PARAMERR,errmsg = "参数错误")

    user = g.user
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender

    return jsonify(errno=RET.OK,errmsg="OK")



@profile_blu.route("/info")
@user_login_data
def user_info():
    user = g.user
    if not user:
        return redirect("/")
    data = {"user":user.to_dict()}

    return render_template("news/user.html",data=data)